<!-- 订单页 -->
<template>
	<view class="order-page">
		<view class="sticky" v-if="technicianStatus">
			<!-- 搜索框 -->
			<view class="search-content">
				<image class="search-img" src="/static/sousuo.png"></image>
				<input placeholder="请搜索订单号" v-model="searchVal" @input="changeInput" @confirm="changeSearch"
					style="width: auto;line-height: 1em; " placeholder-style="font-size:28rpx;color:#A1A1A1;" />
				<image v-if="searchVal" class="icon_close" src="/static/delect.png" @click="close"></image>
			</view>
			<view class="p-fff10">
				<sunui-navbar :items="tabList" lineHeight="70rpx" :isCenter="true" :currentIndex="currentIndex"
					padding="20rpx" :size="90" activeLineBg="#fff" textAlign="center" activeLineWidth="40%"
					activeDirection="center" activeLineHeight="4rpx" bgColor="#fff" :margin="10"
					@change="getChange"></sunui-navbar>
			</view>
			<mescroll-body ref="mescrollRef" :height="windowHeight+'rpx'" @init="mescrollInit" @down="downCallback"
				@up="upCallback" :up="upOption" :down="downOption">
				<view class="card-cls" v-for="(i, j) in list" :key="j">
					<view class="flex-between p-bottom30">
						<!-- 倒计时 -->
						<block v-if="i.status == 1 && Number(timestamps(i.serviceStartTime)) - currTime > 0">
							<view class="v-stauts flex">
								接单时间：
								<sunui-countdown :time="Number(timestamps(i.serviceStartTime)) - currTime" @end="end"
									:timeid="i.id" :showDay="false"></sunui-countdown>
							</view>
						</block>
						<!-- 已超时 -->
						<block v-else-if="i.status == 1 && Number(timestamps(i.serviceStartTime)) - currTime <= 0">
							<view class="v-timeout-stauts flex">已超时</view>
						</block>
						<!-- 已接单后的状态 -->
						<block v-else>
							<view class="flex-align-center order-num">
								<text class="font-overflow" style="max-width: 430rpx;">订单编号：{{ i.orderNumber }}</text>
								<view @click="paste(i.orderNumber)">复制</view>
							</view>
						</block>
						<!-- status订单状态（0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款 -->
						<text class="stauts-cls flex">{{ orderStatusFn(i.status) }}</text>

					</view>
					<view class="flex-align-center">
						<image class="order-img" :src="i.packageList.rotationChart"></image>
						<view class="flex-columns flex1">
							<view class="color333 font32">{{ i.packageList.tradeName }}</view>
							<view :class="i.transferOrder ? 'flex-between' : 'flex-align-center'">
								<view class="appointment-time">预约时间：{{ i.packageList.createdAt.split('T')[0] }}
									{{ i.packageList.createdAt.split('T')[1] }}
								</view>
								<!-- 转单订单——拨打电话功能 -->
								<view class="call-cls flex" v-if="i.transferOrder"
									@click="callPhone(i.technician.mobile)">
									<image mode="heightFix" src="/static/technician/call-icon.png"></image>
								</view>
							</view>
							<view class="flex-align-center">
								<view class="color333 font32 bold">￥{{ i.disbursements }}</view>
								<text class="segmentation">|</text>
								<view class="flex-align-center time-icon">
									<text class="iconfont icon-shijian"></text>
									<view>{{ i.packageList.serviceTime }}分钟</view>
								</view>
							</view>
						</view>
					</view>
					<!-- i.transferOrder 存在则是转单 -->
					<view class="flex-align-center transfer-cls" v-if="i.transferOrder">
						<image src="/static/avater.png"></image>
						<view>转单同事：{{ i.transferOrder }}</view>
					</view>
					<!-- 分割线 -->
					<view class="dashed-line"></view>
					<view class="flex-between">
						<view class="flex-align-center address-cls">
							<text class="iconfont icon-dingweiweizhi"></text>
							<view class="font-overflow">
								{{ i.addressManagement.province }}
								<!-- 省 -->
								{{ i.addressManagement.city }}
								<!-- 市 -->
								{{ i.addressManagement.district }}
								<!-- 区 -->
								{{ i.addressManagement.address }}
								<!-- 详细地址 -->
							</view>
						</view>
						<view class="v-navigation flex-align-center">
							<!-- 需要目的地经纬度 -->
							导航
							<image src="/static/navigation.png"></image>
						</view>
					</view>
					<!-- <view class="flex-align-center">
					<text class="iconfont icon-shijian"></text>
					<view>永州大道梦想家园A栋1单元2023号</view>
					<view>拨打</view>
				</view> -->

					<block v-if="i.status == 1">
						<view class="flex-around m-top40">
							<!-- status 订单状态（0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款） -->
							<view class="refuse-order flex" @click="refuseOrders(i.id)">拒绝</view>
							<!-- transferOrder存在，代表是 “转单技师” 订单，已转技师的单，不可再二次转单 -->
							<view class="refuse-order flex" @click="toTransferOrder(i)" v-if="!i.transferOrder">我要转单
							</view>
							<view class="agree-btn flex" :class="i.transferOrder ? 'big-btn' : ''"
								@click="updateOrders(i.id, 2)">同意接单</view>
						</view>
					</block>
					<block v-if="i.status == 2">
						<view class="service-btn flex" @click="updateOrders(i.id, 3)">开始服务</view>
					</block>
					<block v-if="i.status == 3">
						<view class="service-btn flex" @click="updateOrders(i.id, 4)">结束服务</view>
					</block>
				</view>
			</mescroll-body>
		</view>
		<view v-else>

		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				currTime: new Date().getTime(), // 当前时间
				searchVal: '',
				downOption: {
					auto: false
				},
				// 上拉配置项
				upOption: {
					auto: false
				},
				// status订单状态（0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款
				tabList: [{
						name: '全部',
						id: '' //null
					},
					{
						name: '新订单',
						id: 1
					},
					{
						name: '待服务',
						id: 2
					},
					{
						name: '进行中',
						id: 3
					},
					{
						name: '已完成',
						id: 4
					},
					{
						name: '已取消',
						id: 5
					}
				],
				currentIndex: 0, //自定义索引
				list: [],
				technicianStatus: false,
				windowHeight: '',

			};
		},
		computed: {

			// 日期转13位时间戳
			timestamps: function() {
				return function(day) {
					let timestamps = '';
					/* let time = day.split('T')[0] + ' ' + day.split('T')[1];
						timestamps = new Date(time).getTime(); */
					timestamps = new Date(day).getTime();
					// console.log('timestamps======', timestamps);
					return timestamps;
				};
			},

			// 订单状态
			orderStatusFn: function() {
				return function(status) {
					console.log(status)
					let orderStatus = '';
					// status订单状态（0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款)
					orderStatus =
						status == 0 ? '待付款' : status == 1 ? '待接单' : status == 2 ? '已接单' : status == 3 ? '服务中' :
						status == 4 ? '已完成' : status == 5 ? '已退款' : '';
					return orderStatus;
				};
			},
			...mapGetters('user', ['taskCenter', 'technicianDetails', 'authorizationInformation']),

		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight * 2 - 104;
				}
			});
				
			
		},
		onShow() {
           this.handleLogin()
			this.$at.releaseKey('submit');
		
			
			// this.getAuthorizeInfo(); // 获取当前位置_暂不调用，一直掉用会频繁
		},
		methods: {
			handleLogin() {
				if (uni.getStorageSync('userId')) {
					
					if (this.technicianDetails.authenticationNot !== 3) {
						this.technicianStatus = false
						uni.showModal({
							title: '当前状态',
							content: '当前认证未审核通过无法查看订单',
							success: (res) => {
					
								if (res.confirm) {
									// 需要箭头函数不然会报错
									this.$sun.navSwitch('/pages/index/index')
									console.log('用户点击确定');
								} else if (res.cancel) {
									this.$sun.navSwitch('/pages/index/index')
									console.log('用户点击取消');
								}
					
							}
						});
					} else {
						this.technicianStatus = true,
						this.$nextTick(() => {
							this.mescroll.resetUpScroll();
						});
					}
				} else {
					this.$sun.navRe('/pages/login/login');
					// uni.navigateTo({
					// 	url: `/pages/login/login?tap=1`
					// });
					// 不在跳转到登录页面而是直接用弹框来显示
				}
			},

			

			// 拨打技师电话
			callPhone(phone) {
				this.$sun.phone(phone)
			},
			/* 获取当前经纬度 start */

			//（获取当前位置）
			getAuthorizeInfo() {
				console.log('获取当前位置');
				const that = this;
				uni.authorize({
					scope: 'scope.userLocation',
					success() {
						console.log(11111);
						// 允许授权
						that.getLocations();
					},
					fail() {
						console.log(222222);
						// 拒绝授权
						that.openConfirm();
					}
				});
			},
			//获得地理位置经纬度
			getLocations() {
				console.log('获得地理位置经纬度11');
				wx.getLocation({
					// 将wgs84 改为 gcj02  h5提高精确度
					type: 'gcj02',
					//  geocode: true,   address：地址信息（仅App端支持，需配置geocode为true）
					success: res => {
						this.lat = res.latitude;
						this.lng = res.longitude;
						// 获取当前经纬度  存缓存  在计算差距离的时候 调用
						wx.setStorageSync('lat', this.lat);
						wx.setStorageSync('lng', this.lng);
						console.log('授权成功=====res', res, 'this.lat', this.lat, 'this.lng', this.lng);
						// 调用接口
					},
					fail: res => {
						this.lat = res.latitude;
						this.lng = res.longitude;
						console.log('授权失败res=====', res, 'this.lat', this.lat, 'this.lng', this.lng);
					}
				});
			},
			// 当用户第一次拒绝后再次请求授权
			openConfirm() {
				uni.showModal({
					title: '请求授权当前位置',
					content: '需要获取您的地理位置，请确认授权',
					success: res => {
						// // 调用接口
						this.getLocations();
						if (res.confirm) {
							console.log('请求授权当前位置res.confirm', res);
							// 调用接口
							uni.openSetting(); // 打开地图权限设置
						} else if (res.cancel) {
							uni.showToast({
								title: '你拒绝了授权，无法获得周边信息',
								icon: 'none',
								duration: 10
							});
							this.$sun.toast('定位失败');
						}
					}
				});
			},

			/* 获取当前经纬度 end */

			// 我要转单
			toTransferOrder(item) {
				console.log('我要转单前item========', item);
				this.$sun.navGo('/pages/transfer-order/transfer-order', {
					packageId: item.packageList.id, //套餐id
					siteId: item.siteId, // 站点id
					userId: item.userId, //登录用户的id
					transferOrder: item.technician.id, // 需要转单技师id（old）
					orderId: item.id // 订单id
				});
			},
			getChange(index) {
				this.currentIndex = index;
				this.mescroll.resetUpScroll();
			},

			// 复制订单号
			paste(orderNumber) {
				uni.setClipboardData({
					data: orderNumber
				});
			},
			//监听输入框输入的值
			changeInput() {},
			//输入键盘的搜索
			changeSearch() {
				this.mescroll.resetUpScroll();
			},
			close() {
				this.searchVal = '';
				this.mescroll.resetUpScroll();
			},

			// 我的订单
			/* async queryOrder() {
				const result = await this.$http.get({
					url: this.$api.getSelectTechnicianOrder,
					data: {
						technicianEvaluationId: 2, //技师id
						status: 1 //订单状态（0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款
					}
				});
				if (result.code == 200) {
					console.log('我的订单result.', result);
					this.list = result.data;
				} else {
					this.$sun.toast(result.message);
				}
			}, */

			// 点击导航调用
			async address(tiem) {
				//纬度
				var latitude = parseFloat(tiem.store_addres_lat);
				//经度
				var longitude = parseFloat(tiem.store_addres_lng);
				// 百度地图经纬度转腾讯地图经纬度
				var x_pi = 3.14159265358979324;
				var x = parseFloat(tiem.store_addres_lat) - 0.0065;
				var y = parseFloat(tiem.store_addres_lng) - 0.006;
				var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
				var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
				var lat = (z * Math.cos(theta)).toFixed(7);
				var lng = (z * Math.sin(theta)).toFixed(7);
				//定位地方名称
				var name = tiem.store_name;
				const map = await this.$sun.openLocation({
					//拿到上面的计算好的（百度经纬度转腾讯经纬度）经纬度 进行一个赋值
					lat: lat,
					lng: lng,
					name: tiem.store_name, //名称
					address: tiem.store_addres, //地址
					key: this.menkey //腾讯key
				});
			},
			// 我的订单_接口已改，但数据传值未改
			async upCallback(scroll) {
				let commentSign = this.tabList[this.currentIndex].commentSign;
				let status = commentSign || this.tabList[this.currentIndex].id == -1 ? '' : this.tabList[this
					.currentIndex].id;
				const result = await this.$http.get({
					url: this.$api.getSelectTechnicianOrder,
					data: {
						page: scroll.num,
						limit: 10,
						technicianEvaluationId: wx.getStorageSync('technicianId'), //技师id
						status: this.tabList[this.currentIndex]
							.id //订单状态（0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款
					}
				});
				if (result.code == 200) {

					console.log('result.data', result.data);
					// this.mescroll.endByPage(result.data.list.length, 1);
					this.mescroll.endByPage(result.data.list.length, this.$sun.pagingSum(result.data.count, 10));
					if (scroll.num == 1) this.list = [];
					this.list = this.list.concat(result.data.list);
					console.log('我的订单this.list', this.list, '测试分页总条数', result.data.count, this.$sun.pagingSum(result
						.data.count, 10));

				}
			},
			// 拒绝接单
			refuseOrders(id) {
				uni.showModal({
					// title: '提示',
					confirmColor: '#1890ff',
					content: '确定拒绝该订单吗?',
					success: async res => {
						// 确定
						if (res.confirm) {
							this.updateOrders(id, 5);
						}
						// 取消
						else {
							this.$sun.toast('点击了取消');
						}
					}
				});
			},
			// 订单修改状态
			// status，代表操作后的下一步状态
			async updateOrders(orderId, status) {
				this.$at.uniDoFunc({
					// 键名
					key: 'submit',
					success: async () => {
						//锁定
						this.$at.lockKey('submit');
						const result = await this.$http.put({
							url: this.$api.updateOrder,
							data: {
								id: Number(orderId), //订单id
								status: Number(
									status) //（订单状态（0.待付款 1.待接单 2.已接单 3.服务中 4.已完成 5.已取消/退款）
							}
						});
						if (result.code == 200) {
							// 拒绝接单
							if (status == 5) {
								this.$sun.toast('您已拒绝接单');
								this.getChange(5); //传入下标
							}
							// 同意接单
							if (status == 2) {
								this.$sun.toast('您已同意接单');
								this.getChange(2);
							}
							// 开始服务
							if (status == 3) {
								// this.$sun.toast('开始服务');
								this.getChange(3);
							}
							// 结束服务
							if (status == 4) {
								this.$sun.toast('您已完成该接单');
								this.getChange(4);
							}

							setTimeout(() => {
								this.$at.releaseKey('submit');
							}, 100);
						} else {
							this.$at.releaseKey('submit');
							this.$sun.toast(result.message);
						}
					}
				});
			}
		}
	};
</script>

<style lang="less">
	page {
		background-color: #f7f7f7;
	}

	.order-page {
		.search-content {
			justify-content: center;
			display: flex;
			align-items: center;
			width: 700rpx;
			height: 88rpx;
			margin: 30rpx;
			background: #fff;
			border-radius: 84rpx;

			.search-img {
				width: 30rpx;
				height: 30rpx;
				margin-right: 20rpx;
				margin-left: 40rpx;
			}

			.icon_close {
				padding: 0rpx 15rpx;
				width: 36rpx;
				height: 36rpx;
				margin-right: 30rpx;
			}
		}

		// 订单卡片
		.card-cls {
			margin: 14rpx 22rpx;
			padding: 30rpx 20rpx;
			border-radius: 10rpx;
			background: #fff;

			.v-stauts,
			.v-timeout-stauts {
				border-radius: 0rpx 80rpx 80rpx 0rpx;
				padding: 6rpx 20rpx;
				margin-left: -20rpx;
			}

			.v-stauts {
				color: #fa5;
				background: #fff5ea;
			}

			.v-timeout-stauts {
				color: #f56c6c;
				background: rgb(254, 240, 240);
			}

			.order-num {
				text {
					color: #757575;
				}

				view {
					display: inline-block;
					color: #999;
					padding: 4rpx 10rpx;
					border-radius: 8rpx;
					border: 2rpx solid #bfbfbf;
					margin: 0 22rpx;
				}
			}

			.stauts-cls {
				color: #fff;
				border-radius: 80rpx 0rpx 0rpx 80rpx;
				background: linear-gradient(0deg, #1890ff 0%, #1890ff 100%);
				width: 120rpx;
				height: 48rpx;
				margin-right: -20rpx;
			}

			.order-img {
				width: 136rpx;
				height: 136rpx;
				border-radius: 20rpx;
				margin-right: 20rpx;
			}

			.appointment-time {
				color: #757575;
				margin: 14rpx 0;
			}

			.call-cls {
				border-radius: 50%;
				width: 56rpx;
				height: 56rpx;
				background-color: #1890FF;

				image {
					height: 32rpx;
				}
			}

			// 分割线
			.segmentation {
				color: #d0d0d0;
				margin: 0 18rpx;
			}

			.time-icon {
				color: #26c278;

				text {
					font-size: 28rpx;
				}

				view {
					margin-left: 8rpx;
				}
			}

			// 转单信息
			.transfer-cls {
				margin-top: 34rpx;

				image {
					border-radius: 50%;
					width: 48rpx;
					height: 48rpx;
					margin-right: 14rpx;
				}

				view {
					color: #26c278;
				}
			}

			// 虚线分割
			.dashed-line {
				margin: 28rpx 0;
				border-bottom: 2rpx dashed #e1e1e1;
			}

			.address-cls {
				text {
					font-size: 32rpx;
					color: #a1a1a1;
				}

				view {
					color: #757575;
					margin: 0 10rpx;
				}
			}

			.v-navigation {
				color: #09c680;

				image {
					padding-left: 10rpx;
					width: 38rpx;
					height: 38rpx;
				}
			}

			.service-btn {
				border-radius: 100rpx;
				background: #1890ff;
				margin: 38rpx 28rpx 0;
				height: 74rpx;
				color: #fff;
				font-weight: bold;
				font-size: 32rpx;
			}

			.big-btn {
				width: calc(70% - 20px) !important; // 判断是否转单，2是70-30
			}

			.agree-btn,
			.refuse-order,
			.zd-order {
				width: calc(100% / 3 - 20px); // 判断是否转单，2是70-30
				height: 74rpx;
				color: #fff;
				font-weight: bold;
				font-size: 32rpx;
				border-radius: 100rpx;
			}

			.refuse-order {
				color: #999;
				border: 2rpx solid #999;
				/* color: #f28331;
			border: 2rpx solid #fe7e01; */
				background: #fff;
			}

			.zd-order {
				background: #fff;
				border: 2rpx solid #67c23a;
				color: #67c23a;
			}

			.agree-btn {
				background: #1890ff;
				border: 2rpx solid #1890ff;
				color: #fff;
			}
		}
	}
</style>